<?php

namespace App\Services;

use App\Exceptions\AppException;
use App\Models\Article;
use App\Models\Category;

class CategoryService
{

    /**
     * 获取分类列表
     * @param string $columns 返回的分类字段
     * @param int $articlesCountType 统计分类下的文章数目：0不统计，1只统计已发布的，2统计全部
     * @return mixed
     */
    public function getList(string $columns = '*', int $articlesCountType = 0)
    {
        $query = Category::selectRaw($columns);

        if ($articlesCountType) {
            $query->withCount(['articles' => function ($query) use ($articlesCountType) {
                if ($articlesCountType == 1) {
                    $query->where('status', 1);
                }
            }]);
        }

        $data = $query->orderBy('list_order')
            ->orderBy('id')
            ->get()
            ->toArray();

        return $data;
    }

    public function add(array $data)
    {
        $category = new Category($data);
        $category->save();
    }

    public function find(int $id)
    {
        return Category::findOrFail($id);
    }

    public function edit(array $data)
    {
        $category = Category::find($data['id']);
        $category->fill($data);
        $category->save();
    }

    public function del(int $id)
    {
        $count = Article::where('category_id', $id)->count();
        if ($count) {
            throw new AppException('此分类下尚有' . $count . '篇文章，禁止删除！');
        }

        Category::destroy($id);
    }

    public function getByAlias(string $alias)
    {
        $category = Category::where('alias', $alias)->first();

        if (!$category) {
            throw new AppException('分类不存在');
        }

        return $category;
    }

}
